package org.opens.mybatisplus.controller;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.io.IOUtils;
import org.opens.mybatisplus.service.AudioService;
import org.opens.util.PcmUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.*;

@RequestMapping(value = "/audio")
@RestController
@CrossOrigin(origins = "*", maxAge = 3600, allowCredentials = "true")
public class AudioController {

    private String filePath = "C:\\Users\\张玉明\\Desktop\\ivr电话客服项目\\pcm文件\\test\\";

    private String basePath = "http://39.105.193.94/ivr/";

    private static final String MP3 = "mp3";

    @Autowired
    private AudioService audioService;


    @RequestMapping(value = "/pcm")
    public byte[] getPcmByte() throws IOException {
        File file = new File("C:\\Users\\张玉明\\Desktop\\ivr电话客服项目\\pcm文件\\test\\3f21f7a20d5711ea.pcm");
        FileInputStream fileInputStream = new FileInputStream(file);

        long length = file.length();

        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while (-1 != (n = fileInputStream.read(buffer))) {
            arrayOutputStream.write(buffer, 0, n);
        }

        return arrayOutputStream.toByteArray();
    }

    @RequestMapping(value = "/pcm2")
    public void getLy(HttpServletResponse response) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
        File file = new File("C:\\Users\\张玉明\\Desktop\\ivr电话客服项目\\pcm文件\\test\\3f21f7a20d5711ea.pcm");

        InputStream in = new FileInputStream(file);
        int len = 0;
        byte[] buffer = new byte[1024];
        OutputStream out = response.getOutputStream();
        while ((len = in.read(buffer)) > 0) {
            //将缓冲区的数据输出到客户端浏览器
            out.write(buffer, 0, len);
        }
        out.close();
        in.close();
    }

    @RequestMapping(value = "/wav/bytes")
    public void playWavBytes(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws IOException
    {
        File file = new File("C:\\Users\\张玉明\\Desktop\\ivr电话客服项目\\pcm文件\\test\\3f21f7a20d5711ea.wav");
        InputStream in = new FileInputStream(file);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024*4];
        int n = 0;
        while (-1 != (n = in.read(buffer))) {
            output.write(buffer, 0, n);
        }
        PcmUtils.wirteWavBytes2OutputStream(output.toByteArray(), request, response);
    }

    @RequestMapping(value = "/listen")
    public void getAudio(HttpServletRequest request, HttpServletResponse response, @RequestParam String path) throws Exception {
        if (path != null) {
            /*String range = request.getHeader("Range");
            String[] rs = range.split("\\=");
            range = rs[1].split("\\-")[0];*/
            File file = new File(basePath + path);
            if (!file.exists()) {
                throw new RuntimeException("音频文件不存在 --> 404");
            }
            System.out.println("获取到了文件");
            OutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            long length = file.length();
            // 播放进度
            int count = 0;
            // 播放百分比
            int percent = (int) (length * 1);
            //int irange = Integer.parseInt(range);
            //length = length - irange;

            response.addHeader("Accept-Ranges", "bytes");
            response.addHeader("Content-Length", length + "");
            //response.addHeader("Content-Range", "bytes " + range + "-" + length + "/" + length);
            response.addHeader("Content-Type", "audio/mpeg;charset=UTF-8");

            int len = 0;
            byte[] b = new byte[1024];
            while ((len = fis.read(b)) != -1) {
                os.write(b, 0, len);
                count += len;
                if (count >= percent) {
                    break;
                }
            }
            fis.close();
            os.close();
        }
    }

    @RequestMapping(value = "/listen2")
    public void pcmPlayer(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam String pcmFileName
    ) throws IOException {
        if(StrUtil.isNotEmpty(pcmFileName) && StrUtil.containsAny(pcmFileName, ".pcm")) {
            File file = new File(filePath + pcmFileName);
            if (!file.exists()) {
                throw new RuntimeException("音频文件不存在 --> 404");
            }

            PcmUtils.writePcmFile2OutputStream(file, request, response);
        }
    }

    @RequestMapping(value = "/listen3")
    public void pcmPlayer2(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam String pcmUrl
    ) throws IOException {
        if(StrUtil.isNotEmpty(pcmUrl) && StrUtil.containsAny(pcmUrl, ".pcm", ".wav")) {
            PcmUtils.writePcmUrlFile2OutputStream(basePath + pcmUrl, request, response);
        }
    }

    @RequestMapping(value = "/mp3/download/{fileName}")
    public void downloadWav(
            HttpServletRequest request,
            HttpServletResponse response,
            @PathVariable(value = "fileName") String fileName
    ) {
        System.out.println(111 + fileName);
        InputStream inputStream = audioService.getInputStreamFromLocalByFileName(fileName);
        if(inputStream == null) {
            return;
        }
        String fileType = fileName.substring(fileName.indexOf(".") + 1);
        if(MP3.equals(fileType)) {
            response.setHeader("Content-Type", "audio/mpeg;charset=UTF-8");
        }
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            IOUtils.copy(inputStream, outputStream);
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(inputStream);
        }
    }

}
